package com.zhaungjie.base.utils.ExcelUtil.spi.impl.easy;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.zhaungjie.base.utils.ExcelUtil.ExcelUtil;
import com.zhaungjie.base.utils.ExcelUtil.spi.ExcelUtilWriteHandler;
import com.zhaungjie.base.utils.ExcelUtil.style.CustomCellStyleStrategy;

import java.io.OutputStream;
import java.util.List;

/**
 * excel-util句柄用于简单excel
 *
 * @author zhuangjie
 * @date 2024/06/02
 */
public class ExcelUtilWriteHandlerForEasy extends ExcelUtilWriteHandler {

    public ExcelUtilWriteHandlerForEasy(List<ExcelUtil.ExcelSheet> excelSheetList) {
        super(excelSheetList);
    }

    @Override
    public void outputExcel(OutputStream outputStream) {
        if (outputStream == null) {
            throw new RuntimeException("outputStream is null !");
        }
        try (ExcelWriter excelWriter = EasyExcelFactory.write(outputStream)
                .excelType(ExcelTypeEnum.XLSX)
                .registerWriteHandler(new CustomCellStyleStrategy())
                .build()) {
            for (ExcelUtil.ExcelSheet excelSheet : excelSheetList) {
                WriteSheet writeSheet = EasyExcel.writerSheet(excelSheet.getSheetIndex(), excelSheet.getSheetName()).head(excelSheet.getExcelTable().getSheetTableDataClass()).build();
                excelWriter.write(excelSheet.getExcelTable().getSheetTableDataList(), writeSheet);
            }
        } catch (Exception e) {
            throw new RuntimeException("excel output fail ! " + e.getMessage());
        }

    }

}
